/**
 * Created by mylocc on 15/12/8.
 * 游戏中的websocket
 */

var WebSocket = WebSocket || window.WebSocket || window.MozWebSocket;
$.disconnect_notice = 0;
dwc.GX_WebsocketGameMgr = cc.Class.extend({
    m_websocket : null,
    m_url : "",
    m_needSends:null,
    websocketUrl:null,
    requestCount:0,
    maxRequestCount:5,
    m_cbOpen : null,
    m_cbClose : null,
    ctor : function(__url){
        this.m_websocket = null;
        this.m_url = "";
        this.m_needSends = null;
        this.websocketUrl = null;
        this.maxRequestCount = 10;

        this.m_arrNetWorkListener = [];
        this._initWS(__url);
        this.websocketUrl=__url;
    },
    AddOpenListener : function(_opencallback)
    {
        this.m_cbOpen = _opencallback;
    },
    connected : function(){
        if (this.m_websocket && (this.m_websocket.readyState == WebSocket.OPEN))
        {
            return true;
        }else {
            return false;
        }
    },
    Send : function(__cmd, __data){
        if(!this.m_websocket){
            //TODO 已经被关闭了 处理
            if(this.m_url){
                this._initWS(this.m_url);
            }
        }
        if (this.m_websocket && (this.m_websocket.readyState == WebSocket.OPEN))
        {
            __data = __data || {};

            if($.uid == null || $.uid == undefined)
            {
                $.uid = 0;
            }

            if(!$.token == null || $.uid == undefined)
            {
                $.token = "";
            }
            var obj = {};
            if(typeof __data == "object")
            {
                obj = __data;
                obj.command = __cmd;
                obj.time =  parseInt(new Date().getTime() / 1000);
                if(obj.uid== undefined)
                {
                    obj.uid = parseInt($.uid);
                }
                if (obj.token == undefined)
                {
                    obj.token = $.token;
                }
            }else{
                obj.command = __cmd;
                obj.time =  parseInt(new Date().getTime() / 1000);
                obj.uid = parseInt($.uid) ;
                obj.data = __data;
            }

            //将json格式消息转成字符串
            var msg = JSON.stringify(obj);
            cc.log("my send= : "+msg);
            this.m_websocket.send(msg);
        }
        else
        {
            if(this.m_websocket){
                this.__addSend(__cmd,__data);
                var warningStr = "send text websocket instance wasn't ready...";
                cc.log(warningStr);
            }else{
                cc.log("m_websocket == null");
            }
        }
    },
    __setTimeOut : function(){
        if (this.m_needSends.length > 0)
        {
            setTimeout(this.__Send.bind(this),1000);
        }
    },
    __addSend : function(__cmd,__data){
        this.m_needSends.push({cmd:__cmd,data:__data});
    },
    __Send : function(){
        if (this.m_needSends.length > 0){
            var send = this.m_needSends.pop();
            if(this.m_websocket){
                this.Send(send.cmd,send.data);
                this.__setTimeOut();
            }
        }
    },
    //添加监听器到本地
    AddListener : function(__target, __callback){
        //检验参数个数
        var argLength = arguments.length;
        if(argLength == 2){
            //判断参数
            if((typeof __target != "object") || (typeof __callback != "function")){
                cc.assert("GX_NewWorkManager.AddListener : 参数错误!");
                return;
            }
        }else{
            cc.assert("GX_NetWorkManager.AddListener:参数个数错误!");
            return;
        }

        //如果存在,则重置回调
        for(var i = 0; i < this.m_arrNetWorkListener.length; i++){
            var listener = this.m_arrNetWorkListener[i];
            if(listener
                && listener._target === __target)
            {
                listener._callback = __callback;
                return;
            }
        }

        //不存在,加入队列中
        var listener = {
            _target : __target,
            _callback : __callback
        };
        this.m_arrNetWorkListener.push(listener);

    },

    //移除指定监听器
    RemoveListener : function(__target){
        this.FindAndRemoveListener(__target);
    },

    //查找指定对象监听器并移除
    FindAndRemoveListener : function(__target){
        for(var i = 0; i < this.m_arrNetWorkListener.length; i++){
            var listener = this.m_arrNetWorkListener[i];
            if(listener
                && listener._target === __target)
            {
                this.m_arrNetWorkListener.splice(i, 1);
                return;
            }
        }
    },

    //分发消息
    OnMessage : function(__msg){

        //遍历数组,给所有添加监听的函数分发数据
        for(var i = 0; i < this.m_arrNetWorkListener.length; i++)
        {
            var listener = this.m_arrNetWorkListener[i];
            if(listener && listener._target)
            {
                listener._callback.call(listener._target, __msg);
            }
        }


    },

    Close : function(){
        if(this.m_websocket){
            this.m_websocket.close();
            this.m_websocket = null;
            this.maxRequestCount=0;
            this.OnMessage({command:"Close"});
        }
    },

    _initWS : function(url){
        this.m_url = url;


        var that = this;
        this.m_needSends = [];
        this.m_websocket = new WebSocket(this.m_url);
        this.m_websocket.onopen = function(evt) {
            cc.log(that.m_url  + " was opened.");
            that.__setTimeOut();
            if(that.m_cbOpen)
            {
                that.m_cbOpen(that.m_url);
            }
        };

        this.m_websocket.onmessage = function(evt) {
            //将接收到的数据解析成JSON格式

            try {
                if (evt && evt.data && evt.data.indexOf("heart") == -1) {
                    cc.log("msg " + evt.data);
                }

            }catch (e)
            {
                cc.log(e.name + ":" + e.message);
            }
            if (evt && evt.data)
            {
                //
                var msg = JSON.parse(evt.data);
                that.OnMessage(msg);
                //
            }
        };

        this.m_websocket.onerror = function(evt) {
            cc.log(that.m_url + " init error."+evt.data);


            if($.runningScene && $.disconnect_notice == 0) {
                that.requestCount++;
                if (that.requestCount <= that.maxRequestCount) {
                    setTimeout(function () {
                        that._initWS(that.m_url);
                    }, 3000);
                }
                //that.m_websocket.close();
                //that.m_websocket = null;
                //$.allWebSockets = [];


            }
            /*
            */
            that.OnMessage({command: "onerror"});
            /*
            if($.runningScene && $.disconnect_notice == 0)
            {
                $.disconnect_notice = 1;
                var alert=new dwc.PopupAlert("网络连接已中断，重新登录可继续游戏",function()
                {
                    cc.director.runScene(new dwc.LoginScene());
                });
                $.runningScene.addChild(alert);
                alert.Show();
            }
            */
        };

        this.m_websocket.onclose = function(evt) {
            cc.log(that.m_url + " instance closed.");
            that.m_websocket = null;
            //$.allWebSockets = [];
            that.OnMessage({command:"onclose"});

            /*
            if($.runningScene && $.disconnect_notice == 0)
            {
                that.requestCount++;
                if (that.requestCount <= that.maxRequestCount) {
                    setTimeout(function () {
                        that._initWS(that.m_url);
                    }, 3000);
                }
            };
             */

            /*
            if($.runningScene && $.disconnect_notice == 0)
            {
                $.disconnect_notice = 1;
                var alert=new dwc.PopupAlert("网络连接已中断，重新登录可继续游戏",function()
                {
                    cc.director.runScene(new dwc.LoginScene());
                });
                $.runningScene.addChild(alert);
                alert.Show();
            }
            */
        };
    },
});

var $ = $ || {};
$.websocket = dwc.GX_WebsocketGameMgr;
$.allWebSockets = [];
var createWebSocket = function(url,fore){
    if(url)
    {
        var n =  fore ?  new $.websocket(url) : ( $.allWebSockets[url]  || new $.websocket(url) );
        if(!n.m_websocket){//TODO 关闭处理
            //delete this.allWebSockets[url]; //此处删除出错
            return this.createWebSocket(url,true);
        }
        $.allWebSockets[url] = n;
        return n;
    }else{
        return null;
    }

};